﻿<%@ WebHandler Language="C#" Class="UserTransManage" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;

public class UserTransManage : AjaxHandlerBase
{
    public UserTransManage()
    {
        htTypePermit.Add("del", Constants.Permit_Hr_DelUserChange);
        htTypePermit.Add("edit", Constants.Permit_Hr_EditUserChange);
        htTypePermit.Add("export", Constants.Permit_Hr_ExportUserChange);
    }

    override public void RequestProcess(HttpContext context)
    {
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {       
            case "getlist":     //得到查询列表
                strResponse = getlist(context);
                break;
            case "getmodel":     //得到单条变动记录数据
                strResponse = getmodel(context);
                break;
            case "del":         //删除人事变动记录
                strResponse = DelUserTrans(context);
                break;
            case "edit" :     //更新人事变动记录
                strResponse = UpdateUserTrans(context);
                break;               
            default:
                break;
        }
        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        context.Response.Write(strResponse);
    }
    
    //删除人事变动记录
    private string DelUserTrans(HttpContext context)
    {
        string RecordId = context.Request.Params["modelid"];
        try
        {
            //添加备份
            AddUserTransBak(RecordId, "del");
            
            Chenxin.Lib.Hr.Entity.Hr_PersonnelTransferInfo clhehpti = Chenxin.Lib.Hr.DAL.Hr_PersonnelTransferInfo.GetModel(new Guid(RecordId));
            Chenxin.Lib.Hr.DAL.Hr_PersonnelTransferInfo.Delete(new Guid(RecordId));

            //添加用户操作日志 2010-5-12 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "删除了一个人事变动:员工姓名[" + clhehpti.UserName + "]",
                    OperationType.OperationTypeComboList()["OprType_ChangePersonnel"].ToString()); 
            
            return string.Format("{{success:'1',msg:'删除成功',data:''}}");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message);
        }
    }
    
    //人事变动备份方法
    private void AddUserTransBak(string recordid,string type)
    {
        string str="";
        if(type=="update")
            str="UpdateTime";
        else
            str="DelTime";
        string strSql = string.Format("insert into Hr_PersonnelTransferInfo_bak(RecordId,UserId,UserName,CityId_O,City_O,CompanyId_O,Company_O,DepartId_O,Depart_O,Position_O,EmpLevel_O,CityId_N,City_N,CompanyId_N,Company_N,DepartId_N,Depart_N,Position_N,EmpLevel_N,TransType,TransReason,TransTime,AddTime,AddPerson,{0},OprCityId,OprCityName,OprCompanyId,OprCompanyName,OprDepartId,OprDepartName,OprPersonID,OprPerson) ", str);
        strSql += string.Format(" select newid(),UserId,UserName,CityId_O,City_O,CompanyId_O,Company_O,DepartId_O,Depart_O,Position_O,EmpLevel_O,CityId_N,City_N,CompanyId_N,Company_N,DepartId_N,Depart_N,Position_N,EmpLevel_N,TransType,TransReason,TransTime,AddTime,AddPerson,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}' from Hr_PersonnelTransferInfo where RecordId='{9}'", DateTime.Now.ToString(), CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName,recordid);
        Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
    }
    
    //更新人事变动记录
    private string UpdateUserTrans(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Hr.Entity.Hr_PersonnelTransferInfo model = (Chenxin.Lib.Hr.Entity.Hr_PersonnelTransferInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Hr.Entity.Hr_PersonnelTransferInfo));
            //添加备份
            AddUserTransBak(model.RecordId.ToString(), "update");
            
            //model.AddTime = DateTime.Now;
            //model.AddPerson = CurrentUserInfo.UserName;
            
            if (model.TransType == "离职")
            {
                Chenxin.Lib.Passport.Entity.Hr_UserInfo user = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(model.UserId);
                user.LeaveDate = model.TransTime;
                Chenxin.Lib.Passport.DAL.Hr_UserInfo.Update(user);
            }

            Chenxin.Lib.Hr.Entity.Hr_PersonnelTransferInfo person = Chenxin.Lib.Hr.DAL.Hr_PersonnelTransferInfo.GetModel(model.RecordId);
            model.AddTime = person.AddTime;
            model.AddPerson = person.AddPerson;
            Chenxin.Lib.Hr.DAL.Hr_PersonnelTransferInfo.Update(model);

            if (!string.IsNullOrEmpty(context.Request.Params["synchro"]) && context.Request.Params["synchro"] == "1")
            {
                string strSql = string.Format("update Hr_UserInfo set Position='{0}',EmpLevel='{1}',UpdateTime=getdate() where UserId='{2}'", model.Position_N, model.EmpLevel_N, model.UserId);
                Chenxin.Lib.Passport.DAL.Hr_UserInfo.ExecuteSQL(strSql);
            }
            
            //添加用户操作日志 2010-5-12 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "编辑了一个人事变动:员工姓名[" + model.UserName + "]",
                    OperationType.OperationTypeComboList()["OprType_ChangePersonnel"].ToString()); 
            
            return string.Format("{{success:'1',msg:'更新成功',data:''}}");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message);
        }
    }
    

    //得到单条变动记录数据
    private string getmodel(HttpContext context)
    {
        try
        {
            string recordid = context.Request.Params["modelid"];
            //根据ID得到变动记录
            Chenxin.Lib.Hr.Entity.Hr_PersonnelTransferInfo usertransinfo = Chenxin.Lib.Hr.DAL.Hr_PersonnelTransferInfo.GetModel(new Guid(recordid));
            if (usertransinfo == null)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，找不到对应的变动记录");
            }
            return string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}",
                 Chenxin.Lib.Utility.JsonHelp.Convert2Json(usertransinfo));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message);
        }
    }

    //得到查询列表
    private string getlist(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "RecordID,UserId,usercode,UserName,City_O,Company_O,Depart_O,Position_O,EmpLevel_O,City_N,Company_N,Depart_N,Position_N,EmpLevel_N,TransType,TransTime,AddTime";
            string fieldtablelist = "RecordID,a.UserId,b.usercode as usercode,a.UserName as UserName,City_O,Company_O,Depart_O,Position_O,EmpLevel_O,City_N,Company_N,Depart_N,Position_N,EmpLevel_N,TransType,convert(datetime,TransTime,120) as TransTime,convert(datetime,a.AddTime,120) as AddTime";
            string orderfield = "a.TransTime desc";

            if (!string.IsNullOrEmpty(context.Request["sort"]))
                orderfield = context.Request["sort"];

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaId"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (a.UserId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (DepartId_N = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (DepartId_N in (select departId from Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb.AppendFormat(" AND CompanyId_N = '{0}'", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND CityId_N = '{0}'", cityId);
            else
                sb.AppendFormat(" AND CompanyId_N = '{0}'", CurrentUserInfo.CompanyId.ToString());


            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            //查看权限
            //所有
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllUserTrans))
            {
                sb1.Append(" (1=1) ");
            }
                //城市
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityUserTrans))
            {
                sb1.Append(string.Format("  CityId_N = '{0}' ", CurrentUserInfo.CityId.ToString()));
            }
                //公司
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyUserTrans))
            {
                sb1.Append(string.Format("  CompanyId_N = '{0}' ", CurrentUserInfo.CompanyId.ToString()));
            }
                //部门
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartUserTrans))
            {
                sb1.Append(" EXISTS(");
                sb1.Append(string.Format("Select 1 from Struct_UserDepartRelation M WHERE Hr_PersonnelTransferInfo.DepartId_N=M.DepartId And M.Userid= '{0}' and ViewHrChange=1", CurrentUserInfo.UserId.ToString()));
                sb1.Append(") ");
            }
                //个人
            else
            {
                sb1.Append(string.Format(" a.UserId = '{0}' and (select count(*) from Struct_UserDepartRelation where userid='{0}' and ViewHrChange=1 and IsBelong=1)>0", CurrentUserInfo.UserId.ToString()));
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string usercode = context.Request.QueryString["usercode"];
            string status = context.Request.QueryString["divStatus"];
            string type = context.Request.QueryString["divTransType2"];
            string datetype = context.Request.QueryString["divdate"];
            
            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND {1}>= '{0}'", (stime),datetype));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND {1}< '{0}'", DateTime.Parse(etime).AddDays(1),datetype));
            }
            if (!String.IsNullOrEmpty(usercode))
            {
                sb1.Append(string.Format(" and b.UserCode like '%{0}%'", usercode));
            }
            if (!String.IsNullOrEmpty(status)&&status!="0")
            {
                sb1.Append(string.Format(" and b.Status='{0}'", status));
            }
            if (!String.IsNullOrEmpty(type))
            {
                if (type != "非离职和退休")
                {
                    sb1.Append(string.Format(" and a.TransType='{0}'", type));
                }
                else
                {
                    sb1.Append(string.Format(" and a.TransType not in('离职','退休') "));
                }
            }

            //判断权限范围结束////////////////////////////////////////////
            System.Data.DataSet list = null;
            list = Chenxin.Lib.Hr.DAL.Hr_PersonnelTransferInfo.GetList(
                iPageIndex, iPageSize, orderfield, "Hr_PersonnelTransferInfo as a left join  Hr_UserInfo as b ON a.UserId = b.UserId", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)list.Tables[1].Rows[0][0];

            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',{2}}}}}", "成功", count, JsonHelp.Convert2Json(list.Tables[0]));
            //string strHtml = "";
            //if (!GetKeyListHtml(list, out strHtml))
            //{
            //    return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            //}
            //list.Dispose();
            //list = null;
            //return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\" style=\"width:1050px;\">");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"80\">员工姓名</th>");
            sb.Append("<th width=\"80\">原城市</th>");
            sb.Append("<th width=\"80\">原公司</th>");
            sb.Append("<th width=\"80\">原部门</th>");
            sb.Append("<th width=\"80\" >原职务</th>");
            sb.Append("<th width=\"80\" >原职级</th>");
            sb.Append("<th width=\"80\">新城市</th>");
            sb.Append("<th width=\"80\">新公司</th>");
            sb.Append("<th width=\"80\">新部门</th>");
            sb.Append("<th width=\"80\">新职务</th>");
            sb.Append("<th width=\"80\">新职级</th>");
            sb.Append("<th width=\"80\">变动类型</th>");
            sb.Append("<th width=\"80\">变动时间</th>");
            sb.Append("</tr></thead><tbody>");

            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["RecordID"].ToString());
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UserName", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "City_O", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Company_O", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Depart_O", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Position_O", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EmpLevel_O", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "City_N", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Company_N", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Depart_N", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Position_N", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EmpLevel_N", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TransType", ""));
                sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TransTime", DateTime.Today));
                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }

    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        context.Response.ContentType = "text/plain";
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        string op = context.Request.Params["op"];

        if (String.IsNullOrEmpty(op))
        {
            strMsg = "{success:0,msg:'操作参数有误！',data:''}";
            return false;
        }
        op = op.ToLower();

        string code = context.Request.Params["code"];
        if (op.Equals("checkpermit"))
        {
            if (String.IsNullOrEmpty(code))
            {
                strMsg = "{success:0,msg:'权限检查参数有误！',data:''}";
                return false;
            }
            code = code.ToLower();
            //权限判断
            //传递参数用
            System.Collections.Hashtable per = new System.Collections.Hashtable();
            System.Collections.Hashtable confine = new System.Collections.Hashtable();

            //编辑客户
            if (code.Equals("edit"))
            {
                if (CurrentUserInfo.ContainsPermit(Constants.Permit_Hr_SynchroUserChange))
                {
                    strMsg = "{success:1,msg:'',data:{permit:{editall:true}}}";
                    return true;
                }
                else
                {
                    strMsg = "{success:1,msg:'',data:{permit:{editall:false}}}";
                    return true;
                }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }

}